package com.css.dzj.dzjap.modules.lawenforcesuper.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.css.dzj.dzjap.common.util.*;
import com.css.dzj.dzjap.modules.apunit.entity.ApUnitEntity;
import com.css.dzj.dzjap.modules.apunit.service.ApunitService;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.ApDeptExtractInfoEntity;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.ApDeptExtractRelationEntity;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.QApDeptExtractInfoEntity;
import com.css.dzj.dzjap.modules.lawenforcesuper.entity.QApDeptExtractRelationEntity;
import com.css.dzj.dzjap.modules.lawenforcesuper.mapper.ApDeptExtractInfoMapper;
import com.css.dzj.dzjap.modules.lawenforcesuper.mapper.ApDeptExtractRelationMapper;
import com.css.dzj.dzjap.modules.lawenforcesuper.service.ApDeptExtractService;
import com.css.dzj.dzjap.modules.lawenforcesuper.view.ApDeptExtractView;
import com.css.dzj.dzjap.modules.publick.dao.PublicDao;
import com.css.dzj.dzjap.modules.publick.entity.ApPublicEntity;
import com.css.dzj.dzjap.modules.todolist.entity.ApTodoEntity;
import com.css.dzj.dzjap.modules.todolist.service.ApTodoService;
import com.css.dzj.dzjap.sys.user.entity.LoginUser;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 安评单位抽出service实现类
 * @author limanman
 */
@Service
public class ApDeptExtractServiceImpl implements ApDeptExtractService {
    @Autowired
    private ApDeptExtractInfoMapper apDeptExtractInfoMapper;
    @Autowired
    private ApDeptExtractRelationMapper apDeptExtratRelationMapper;
    @Autowired
    private ApunitService apunitService;
    @Autowired
    private JPAQueryFactory jpaQueryFactory;
    // 公开公告Dao
    @Autowired
    private PublicDao publicDao;
    @Autowired
    private ServiceUtil serviceUtil;
    @Autowired
    private ApTodoService apTodoService;
    @Override
    @Transactional
    public R saveApDeptExtract(ApDeptExtractInfoEntity apDeptExtractInfoEntity, HttpServletRequest request) {
        try {
            if (apDeptExtractInfoEntity ==null || "".equals(apDeptExtractInfoEntity)){
                throw new RuntimeException("新增不能为空");
            }
            /**
             * 获取suser
             */
            R r = serviceUtil.getUserInfoByRequest(request);
            String suserName = "";
            String location = "";
            String address="";
            String userUnit ="";
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                /**
                 * 获取用户名
                 */
                suserName =userInfo.getLoginName();
                /**
                 * 获取用户的省份
                 */
                String orgName = userInfo.getOrgName();
                location = orgName.replace("地震局","");
                address = userInfo.getAddress();
                userUnit= userInfo.getOrgName();
            }

            apDeptExtractInfoEntity.setId(UUID.randomUUID().toString());
            apDeptExtractInfoEntity.setCreateTime(new Date());
            apDeptExtractInfoEntity.setCreatePerson(suserName);
            apDeptExtractInfoEntity.setCreatePersonLocation(location);
            apDeptExtractInfoEntity.setEnterpriseNotice(Constant.PUBLICNO);

            apDeptExtractInfoEntity.setCreatePersonUnit(userUnit);
            String apDeptExtractInfoEntityId = apDeptExtractInfoEntity.getId();
            /**
             * 抽出的总数
             */
            Integer sumNum = apDeptExtractInfoEntity.getTaskNum();
            if (sumNum<=0){
                throw new RuntimeException("抽取安评单位总数不能为0");
            }

            List<ApDeptExtractRelationEntity> apDeptExtratRelationEntities = new ArrayList();
            ApDeptExtractRelationEntity apDeptExtratRelationEntity ;

            /**
             * 数据库数量
             */
            List<ApUnitEntity> apUnitEntities;

            if(Constant.LOCATIONZG.equals(location)){
                apUnitEntities =  apunitService.querySbUnit();
            }else{
                apUnitEntities =  apunitService.queryByLocation(location);
            }

            if(sumNum<=apUnitEntities.size()){
                /**
                 * 随机选出的数量
                 */
                List<ApUnitEntity> randomApUnitEntities = RandomUtil.ramdonExtract(apUnitEntities,sumNum.toString());
                if(!StringUtils.isEmpty(randomApUnitEntities) && randomApUnitEntities.size()>0 ){
                    for (ApUnitEntity apUnitEntity:randomApUnitEntities){
                        if (!StringUtils.isEmpty(apUnitEntity)){
                            apDeptExtratRelationEntity = new ApDeptExtractRelationEntity();
                            apDeptExtratRelationEntity.setTaskId(apDeptExtractInfoEntityId);
                            apDeptExtratRelationEntity.setRecordId(apUnitEntity.getId());
                            apDeptExtratRelationEntity.setCreateTime(new Date());
                            apDeptExtratRelationEntity.setCreatePerson(suserName);
                            apDeptExtratRelationEntity.setCqStatus(Constant.UNEXTRACT);
                            apDeptExtratRelationEntities.add(apDeptExtratRelationEntity);
                        }
                    }
                }
            }else{
                throw new RuntimeException("符合抽取条件的安评单位数量不足！");
            }

            if(!StringUtils.isEmpty(apDeptExtratRelationEntities) && apDeptExtratRelationEntities.size()>0){
                apDeptExtratRelationMapper.saveAll(apDeptExtratRelationEntities);
            }

            apDeptExtractInfoMapper.save(apDeptExtractInfoEntity);
            return R.ok("保存成功！").put("taskId",apDeptExtractInfoEntityId);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }

    }

    /**
     * 查询所有安评抽取任务
     * @param pageable
     * @param taskTitle
     * @return
     */
    @Override
    public QueryResults<ApDeptExtractInfoEntity> queryExtract(Pageable pageable, String taskTitle,HttpServletRequest request) {
        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            String location = "";
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                String orgName = userInfo.getOrgName();
                location = orgName.replace("地震局","");
            }

            if (location!=null && !"".equals(location)){
                QApDeptExtractInfoEntity qApDeptExtractInfoEntity = QApDeptExtractInfoEntity.apDeptExtractInfoEntity;
                Predicate predicate = qApDeptExtractInfoEntity.isNotNull().or(qApDeptExtractInfoEntity.isNull());
                predicate = ("".equals(taskTitle) || taskTitle == null) ? predicate : ExpressionUtils.and(predicate, qApDeptExtractInfoEntity.taskTitle.like("%"+taskTitle+"%"));
                if (!Constant.LOCATIONZG.equals(location)){
                    predicate = ("".equals(location) || location==null)?predicate:ExpressionUtils.and(predicate,qApDeptExtractInfoEntity.createPersonLocation.like("%"+location+"%"));
                }
                QueryResults<ApDeptExtractInfoEntity> page  = jpaQueryFactory
                        .selectFrom(qApDeptExtractInfoEntity)
                        .where(predicate)
                        .orderBy(qApDeptExtractInfoEntity.createTime.desc())
                        .offset(pageable.getOffset())
                        .limit(pageable.getPageSize())
                        .fetchResults();
                QueryResults queryResults = new QueryResults(page.getResults(),page.getLimit(),page.getOffset(),page.getTotal());
                return queryResults;
            }else {
                throw new RuntimeException("用户所在省份不能为空！");
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 根据任务标题查询所有安评抽取任务（不分省份） --- 用于开展监管工作情况
     * @param pageable
     * @param taskTitle
     * @return
     */
    @Override
    public QueryResults<ApDeptExtractInfoEntity> queryAllExtract(Pageable pageable, String taskTitle,HttpServletRequest request) {
        try {
            R r = serviceUtil.getUserInfoByRequest(request);
            String location = "";
            if(r.getCode().equals("200")){
                LoginUser userInfo =  (LoginUser)r.get("data");
                String orgName = userInfo.getOrgName();
                location = orgName.replace("地震局","");
            }


            QApDeptExtractInfoEntity qApDeptExtractInfoEntity = QApDeptExtractInfoEntity.apDeptExtractInfoEntity;
            Predicate predicate = qApDeptExtractInfoEntity.isNotNull().or(qApDeptExtractInfoEntity.isNull());
            predicate = ("".equals(taskTitle) || taskTitle == null) ? predicate : ExpressionUtils.and(predicate, qApDeptExtractInfoEntity.taskTitle.like("%"+taskTitle+"%"));

            QueryResults<ApDeptExtractInfoEntity> page  = jpaQueryFactory
                    .selectFrom(qApDeptExtractInfoEntity)
                    .where(predicate)
                    .orderBy(qApDeptExtractInfoEntity.createTime.desc())
                    .offset(pageable.getOffset())
                    .limit(pageable.getPageSize())
                    .fetchResults();
            QueryResults queryResults = new QueryResults(page.getResults(),page.getLimit(),page.getOffset(),page.getTotal());
            return queryResults;

        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 根据任务id查询本次安评单位抽取信息表（）
     * @param taskId
     * @return
     */
    @Override
    public ApDeptExtractInfoEntity queryExtractInfoById(String taskId) {
        if(!"".equals(taskId) && taskId!=null){
            return apDeptExtractInfoMapper.findById(taskId).get();
        }else {
            return null;
        }
    }

    /**
     * 中间查询，根据任务id查询安评单位抽取关联表
     * @param pageable
     * @param taskId
     * @return
     */
    @Override
    public QueryResults<ApDeptExtractRelationEntity> queryExtractApDept(Pageable pageable,String taskId) {
        try {
            QApDeptExtractRelationEntity qApDeptExtractRelationEntity = QApDeptExtractRelationEntity.apDeptExtractRelationEntity;
            Predicate predicate = qApDeptExtractRelationEntity.isNotNull().or(qApDeptExtractRelationEntity.isNull());
            predicate = ("".equals(taskId) || taskId == null) ? predicate : ExpressionUtils.and(predicate, qApDeptExtractRelationEntity.taskId.eq(taskId));

            return jpaQueryFactory.selectFrom(qApDeptExtractRelationEntity)
                    .where(predicate)
                    .offset(pageable.getOffset())
                    .limit(pageable.getPageSize())
                    .fetchResults();
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 通过抽取任务id查询抽取的所有安评单位
     * @param pageable
     * @param taskId
     * @return
     */
    @Override
    public QueryResults<ApDeptExtractView> queryApUnitByTaskId(Pageable pageable,String taskId,HttpServletRequest request) {

        /**
         * 获取suser
         */
        R r = serviceUtil.getUserInfoByRequest(request);
        String suserName = "";
        String location = "";
        String address="";
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            /**
             * 获取用户名
             */
            suserName =userInfo.getLoginName();
            /**
             * 获取用户的省份
             */
            String orgName = userInfo.getOrgName();
            location = orgName.replace("地震局","");
            address = userInfo.getAddress();
        }

        if (taskId!=null && !"".equals(taskId)){
            QueryResults<ApDeptExtractRelationEntity> page = queryExtractApDept(pageable,taskId);
            ApUnitEntity apUnitEntity =null;
            List<ApDeptExtractView> apDeptExtractViews = new ArrayList<ApDeptExtractView>();
            List<ApDeptExtractRelationEntity> apDeptExtractRelationEntityList=page.getResults();
            ApDeptExtractView apDeptExtractView;
            for(ApDeptExtractRelationEntity apDeptExtractRelationEntity:apDeptExtractRelationEntityList){
                apUnitEntity = apunitService.queryById(apDeptExtractRelationEntity.getRecordId());
                if(!StringUtils.isEmpty(apUnitEntity)){
                    apDeptExtractView = new ApDeptExtractView();
                    apDeptExtractView.setTaskId(apDeptExtractRelationEntity.getTaskId());
                    apDeptExtractView.setRecordId(apDeptExtractRelationEntity.getRecordId());
                    apDeptExtractView.setCqStatus(apDeptExtractRelationEntity.getCqStatus());
                    apDeptExtractView.setUnitName(apUnitEntity.getUnitName());
                    apDeptExtractView.setUniscid(apUnitEntity.getUniscid());
                    apDeptExtractView.setRegistAddr(apUnitEntity.getRegistAddr());
                    apDeptExtractView.setSpPerson(apUnitEntity.getSpPerson());
                    apDeptExtractView.setSpOrg(apUnitEntity.getSpOrg());
                    apDeptExtractView.setSpStatus(apUnitEntity.getSpStatus());
                    apDeptExtractView.setSpTime(apUnitEntity.getSpTime());
                    apDeptExtractView.setSbStatus(apUnitEntity.getSbStatus());
                    apDeptExtractView.setUnitRegistTime(apUnitEntity.getUnitRegistTime());
                    apDeptExtractView.setLocation(location);
                    apDeptExtractViews.add(apDeptExtractView);
                }
            }
            if(!StringUtils.isEmpty(apDeptExtractViews) && apDeptExtractViews.size()>0){
                QueryResults<ApDeptExtractView> queryResults = new QueryResults(apDeptExtractViews,page.getLimit(),page.getOffset(),page.getTotal());
                return  queryResults;
            }else {
                return null;
            }
        }else {
        throw new RuntimeException("taskId不能为空！");
        }
    }

    /**
     * 修改是否抽取了执法人员状态
     * @param taskId
     * @param recordId
     */
    @Override
    @Transactional
    public void updApDeptExtractRelation(String taskId, String recordId) {
        try {
            if(!"".equals(taskId) && taskId!=null && recordId!=null && !"".equals(recordId)){
                QApDeptExtractRelationEntity q = QApDeptExtractRelationEntity.apDeptExtractRelationEntity;
                jpaQueryFactory.update(q)
                        .set(q.cqStatus, Constant.EXTRACT)
                        .where(q.taskId.eq(taskId),q.recordId.eq(recordId))
                        .execute();
            }else {
                throw new RuntimeException();
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        }
    }

    @Override
    @Transactional
    public void addPulic(ApPublicEntity apPublicEntity,HttpServletRequest request) {
        if(StringUtils.isEmpty(apPublicEntity.getRelationId())){
            throw new RuntimeException("拟制公告失败");
        }
        R r = serviceUtil.getUserInfoByRequest(request);
        if(r.getCode().equals("200")){
            LoginUser userInfo =  (LoginUser)r.get("data");
            apPublicEntity.setCreateUser(userInfo.getLoginName());
            apPublicEntity.setOrganName(userInfo.getOrgName());
        }
        // 根据此请求路径+RelationId 前端axios获取信息
        apPublicEntity.setPublicUrl("/dzjap/apDeptExtract/getById");
        apPublicEntity.setRevokeg(Constant.REVOKE_NO);
        // 设置默认值
        apPublicEntity.setDelFlag(Constant.NO_DELETE);
        apPublicEntity.setCreateTime(new Date());
        apPublicEntity.setInputenTime(new Date());

        // 设置类型8：监管任务，根据此类型前端判断进入哪个页面
        apPublicEntity.setFictionType("7");
        publicDao.save(apPublicEntity);
        //调取待办接口
        ApTodoEntity apTodoEntity = new ApTodoEntity();
        apTodoEntity.setStatus(Constant.STATUSDB);
        apTodoEntity.setCreateTime(new Date());
        apTodoEntity.setDelFlag(Constant.NO_DELETE);
        apTodoEntity.setTitle(apPublicEntity.getTitle()+"公开公告审批");
        apTodoEntity.setLinkId(apPublicEntity.getPublicId());
        //审批员才能看到相应的审批
        apTodoEntity.setStation("地震部门审定人员");
        //去审批页
        apTodoEntity.setUrl("../todolist/publick.html");
        apTodoEntity.setLocation(apPublicEntity.getOrganName());
        apTodoEntity.setCreatePerson(ServiceUtil.getLoginName(request));
        //审批的业务
        apTodoEntity.setTypeFlag(Constant.TYPRFLAGSS);
        apTodoService.saveDB(apTodoEntity);
        QApDeptExtractInfoEntity q=QApDeptExtractInfoEntity.apDeptExtractInfoEntity;
        jpaQueryFactory.update(q).set(q.enterpriseNotice,"1").where(q.id.eq(apPublicEntity.getRelationId())).execute();
    }

    @Override
    public List<ApDeptExtractInfoEntity> findAll() {
        List<ApDeptExtractInfoEntity> listAp=findAll();
        return listAp;
    }

    @Override
    public List<ApUnitEntity> findDeptByTaskId(String taskId) {
        QApDeptExtractRelationEntity qApDeptExtractRelationEntity = QApDeptExtractRelationEntity.apDeptExtractRelationEntity;
        List<ApDeptExtractRelationEntity> listApDept=jpaQueryFactory.selectFrom(qApDeptExtractRelationEntity)
                .where(qApDeptExtractRelationEntity.taskId.eq(taskId)).fetch();
        if(!StringUtils.isEmpty(listApDept) && listApDept.size()>0){
            List<ApUnitEntity> listAp=new ArrayList<>();
            for(ApDeptExtractRelationEntity listD: listApDept){
               ApUnitEntity apUnitEntity=apunitService.queryById(listD.getRecordId());
               if(apUnitEntity != null) {
                   listAp.add(apUnitEntity);
               }
            }
            return listAp;
        }else {
            return null;
        }
    }
    /**
     * 查询所有部门抽取信息
     * @return
     */
    @Override
    public List queryAllUnitMsg() {
        QApDeptExtractInfoEntity q = QApDeptExtractInfoEntity.apDeptExtractInfoEntity;
        Predicate predicate = q.isNotNull().or(q.isNull());
        List<ApDeptExtractInfoEntity> list = jpaQueryFactory.selectFrom(q)
                .where(predicate)
                .orderBy(q.createTime.desc())
                .fetch();
        return list;
    }

}
